package com.wbs.shop.nuby.widget;


import android.content.Context;
import android.content.res.TypedArray;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.wbs.shop.nuby.R;

public class AddWidget extends FrameLayout {
    private TextView tv_count;
    private int number = 1;
    private int minNumber;
    private OnNumberChangListener mOnNumberChangListener;

    public interface OnNumberChangListener {

        void onNumberChang(View view, int number);
    }

    public void setOnNumberChangListener(OnNumberChangListener mOnNumberChangListener) {
        this.mOnNumberChangListener = mOnNumberChangListener;
    }

    public AddWidget(@NonNull Context context) {
        super(context);
    }

    public AddWidget(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        inflate(context, R.layout.view_addwidget, this);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.AddWidget, 0, 0);
        minNumber = typedArray.getInt(R.styleable.AddWidget_min_number, 1);
        typedArray.recycle();
        View add = findViewById(R.id.iv_add);
        View sub = findViewById(R.id.iv_sub);
        tv_count = (TextView) findViewById(R.id.tv_count);
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                number++;
                setNumber(number);
                if (mOnNumberChangListener != null) {
                    mOnNumberChangListener.onNumberChang(AddWidget.this, number);
                }
            }
        });
        sub.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (number <= minNumber)
                    return;
                number--;
                setNumber(number);
                if (mOnNumberChangListener != null) {
                    mOnNumberChangListener.onNumberChang(AddWidget.this, number);
                }
            }
        });
        setNumber(number);
    }

    public void setNumber(int number) {
        this.number = number;
        tv_count.setText(String.valueOf(this.number));
    }

    public int getNumber() {
        return this.number;
    }
}
